package com.dm.cloud.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.log4j.Log4j2;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

@Log4j2
public class EntityUtils {

    /**
     * 移除实体类中为null的字段
     * @param entity
     * @return
     */
    public static<T>  Object removeNullField(T entity) {

        Map<String,Object> result = new LinkedHashMap<>();

        //遍历实体类中的字段
        try {
            Class cls = entity.getClass();
            Field[] fields = cls.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                f.setAccessible(true);
                //判断是否为NULL
                if (ObjectUtils.isNotNull(f.get(entity))) {
                    result.put(f.getName(), f.get(entity));
                }
            }
        }catch (Exception ex){
           log.warn("实体类字段整理异常",ex.getCause());
        }

        //serialVersionUID 有值也不返回
        result.remove("serialVersionUID");

        return result;
    }
}
